<template>
  <view class="exhibition-page">
    <!-- 自定义导航栏 -->
    <up-navbar title="" :bgColor="bgColor" height="50" fixed placeholder>
      <template #left>
        <text>书法展览</text>
      </template>
    </up-navbar>

    <view class="content">
      <!-- 搜索框和筛选 -->
      <view class="search-section">
        <!-- 直接显示搜索框 -->
        <view class="search-bar-container">
          <up-search placeholder="搜索虚拟展馆名称、主题" shape="square" v-model="searchKeyword" :clearabled="true"
            @search="handleSearch" />
        </view>

        <view class="filter-btn" @click="showFilterModal">
          <up-icon name="list" color="#666" size="16"></up-icon>
        </view>
      </view>

      <!-- 筛选标签 -->
      <view class="filter-tags" v-if="activeFilters.length > 0">
        <scroll-view scroll-x class="tags-scroll">
          <view class="tag-list">
            <view class="filter-tag" v-for="(filter, index) in activeFilters" :key="index" @click="removeFilter(index)">
              <text>{{ filter }}</text>
              <up-icon name="close" size="12" color="#666"></up-icon>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 展馆列表 -->
      <view class="section">
        <view class="section-header">
          <view class="section-title">
            <up-icon name="grid" color="#4caf50" size="18"></up-icon>
            <text>全部虚拟展馆</text>
          </view>
          <view class="sort-btn" @click="showSortModal">
            <text>{{ currentSort.label }}</text>
            <up-icon name="arrow-down" color="#999" size="12"></up-icon>
          </view>
        </view>

        <!-- 使用 hall-list 组件替换原来的展馆列表 -->
        <gallery-list :list-data="filteredExhibitions" :isLoading="loading"  @item-click="goExhibition"/>

        <!-- 加载更多 -->
        <up-loadmore height="50vh" :status="loadStatus" />
      </view>
    </view>

    <!-- 筛选模态框 -->
    <up-popup :show="showFilter" mode="bottom" :round="true" @close="showFilter = false">
      <view class="filter-modal">
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <text class="filter-reset" @click="resetFilters">重置</text>
        </view>

        <view class="filter-section">
          <text class="filter-label">展览类型</text>
          <view class="filter-options">
            <text class="filter-option" :class="{ active: selectedFilters.category === category }"
              v-for="category in filterOptions.categories" :key="category" @click="selectFilter('category', category)">
              {{ category }}
            </text>
          </view>
        </view>

        <view class="filter-section">
          <text class="filter-label">展览风格</text>
          <view class="filter-options">
            <text class="filter-option" :class="{ active: selectedFilters.style === style }"
              v-for="style in filterOptions.styles" :key="style" @click="selectFilter('style', style)">
              {{ style }}
            </text>
          </view>
        </view>

        <view class="filter-section">
          <text class="filter-label">展览状态</text>
          <view class="filter-options">
            <text class="filter-option" :class="{ active: selectedFilters.status === status }"
              v-for="status in filterOptions.status" :key="status" @click="selectFilter('status', status)">
              {{ status }}
            </text>
          </view>
        </view>

        <view class="filter-actions">
          <up-button type="primary" text="确认筛选" @click="applyFilters" customStyle="margin-top: 30rpx;"></up-button>
        </view>
      </view>
    </up-popup>

    <!-- 排序模态框 -->
    <up-action-sheet :show="showSort" :actions="sortOptions" title="选择排序方式" @select="handleSort"
      @close="showSort = false" />
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { onReachBottom } from "@dcloudio/uni-app";
import GalleryList from "@/components/gallery-list/gallery-list.vue";
import Apis from '@/api/index.js';
import { usePagination } from 'alova/client';

// 响应式数据
const showFilter = ref(false);
const showSort = ref(false);
const searchKeyword = ref("");
const bgColor = ref('#fff');

// 筛选相关
const activeFilters = ref([]);
const selectedFilters = reactive({
  category: "",
  style: "",
  status: "",
});

const filterOptions = reactive({
  categories: ["书法专题", "绘画艺术", "文物展示", "现代艺术", "民间手工"],
  styles: ["中国古典", "现代简约", "民族风情", "国际融合", "创新实验"],
  status: ["正在展出", "即将开放", "精品推荐", "热门展览"],
});

// 排序选项
const sortOptions = reactive([
  { name: "综合排序", value: "default" },
  { name: "热度从高到低", value: "visit_desc" },
  { name: "评分从高到低", value: "rating_desc" },
  { name: "作品数量从多到少", value: "artwork_desc" },
  { name: "最新开放", value: "time_desc" },
]);

const currentSort = ref(sortOptions[0]);

// 使用 usePagination 管理展馆列表数据
const {
  loading,
  data: exhibitions,
  isLastPage,
  page,
  refresh,
  reload
} = usePagination(
  // Method instance 获取函数
  (page, pageSize) => {
    // 构造请求参数
    const params = {
      pageNum: page,
      pageSize: pageSize,
      // 添加筛选条件
      category: selectedFilters.category || undefined,
      style: selectedFilters.style || undefined,
      status: selectedFilters.status || undefined,
      // 添加搜索关键词
      keyword: searchKeyword.value || undefined,
      // 添加排序参数
      sort: currentSort.value.value !== "default" ? currentSort.value.value : undefined
    };

    // 返回 Method 实例
    return Apis.wx_gallery.getGalleryList({
      params: params
    });
  },
  {
    // 初始数据
    initialData: { rows: [], total: 0 },
    initialPage: 1,
    initialPageSize: 10,
    append: true,
    data: res => res.rows,
    total: res => res.total,
    // 监听筛选条件变化，自动重新请求
    watchingStates: [selectedFilters, searchKeyword, currentSort]
  }
);

// 计算加载状态
const loadStatus = computed(() => {
  if (loading.value) {
    return "loading";
  } else if (isLastPage.value) {
    return "noMore";
  } else {
    return "loadmore";
  }
});

// 筛选后的展馆列表
const filteredExhibitions = computed(() => {
  // 注意：由于现在直接从服务器获取已筛选的数据，这里只需要返回原始列表
  return exhibitions.value || [];
});

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = "";
};

// 处理搜索
const handleSearch = () => {
  // 搜索时刷新数据，usePagination会自动监听searchKeyword的变化
  refreshExhibitions();
  updateActiveFilters();
};

const showFilterModal = () => {
  showFilter.value = true;
};

const showSortModal = () => {
  showSort.value = true;
};

const selectFilter = (type, value) => {
  selectedFilters[type] = selectedFilters[type] === value ? "" : value;
  // 由于usePagination监听了selectedFilters，这里不需要手动刷新
};

const applyFilters = () => {
  showFilter.value = false;
  // 由于usePagination监听了selectedFilters，这里不需要手动刷新
  updateActiveFilters();
};

const updateActiveFilters = () => {
  activeFilters.value = [];
  if (searchKeyword.value) {
    activeFilters.value.push(`搜索: ${searchKeyword.value}`);
  }
  if (selectedFilters.category) {
    activeFilters.value.push(selectedFilters.category);
  }
  if (selectedFilters.style) {
    activeFilters.value.push(selectedFilters.style);
  }
  if (selectedFilters.status) {
    activeFilters.value.push(selectedFilters.status);
  }
};

const removeFilter = (index) => {
  const filter = activeFilters.value[index];
  if (filter.includes("搜索:")) {
    searchKeyword.value = "";
  } else if (filterOptions.categories.includes(filter)) {
    selectedFilters.category = "";
  } else if (filterOptions.styles.includes(filter)) {
    selectedFilters.style = "";
  } else if (filterOptions.status.includes(filter)) {
    selectedFilters.status = "";
  }
  // 由于usePagination监听了这些状态，这里不需要手动刷新
  updateActiveFilters();
};

const resetFilters = () => {
  selectedFilters.category = "";
  selectedFilters.style = "";
  selectedFilters.status = "";
  searchKeyword.value = "";
  activeFilters.value = [];
  // 由于usePagination监听了这些状态，这里不需要手动刷新
};

const handleSort = (item) => {
  currentSort.value = item;
  showSort.value = false;
  uni.showToast({
    title: `已按${item.name}排序`,
    icon: "none",
  });
  // 由于usePagination监听了currentSort，这里不需要手动刷新
};

// 跳转到展厅详情页
const goExhibition = (data) => {
  uni.navigateTo({
    url: "/gallery_pages/gallery/detail?galleryId=" + data.galleryId,
  });
};

// 上拉加载更多
const loadMore = () => {
  // 如果不是最后一页且不在加载中，则加载下一页
  if (!isLastPage.value && !loading.value) {
    page.value++;
  }
};

// 刷新展馆列表数据
const refreshExhibitions = () => {
  // 使用 usePagination 的 refresh 方法刷新第一页数据
  refresh();
};

// 重新加载当前页数据
const reloadExhibitions = () => {
  // 使用 usePagination 的 reload 方法重新加载当前页数据
  reload();
};

onMounted(() => {
  // 页面加载完成后的初始化操作
  refreshExhibitions();
});

// 监听页面滚动到底部
onReachBottom(() => {
  loadMore();
});
</script>

<style lang="scss" scoped>
.exhibition-page {
  min-height: 100vh;
  background-color: #f5f6fa;
}

.content {
  padding: 10rpx 10rpx 36rpx;
}

// 搜索区域
.search-section {
  display: flex;
  align-items: center;
  // gap: 10rpx;
  // margin: 10rpx 0 20rpx;
  background-color: #ffffff;

  .search-bar-container {
    flex: 1;
  }

  .filter-btn {
    width: 80rpx;
    height: 80rpx;
    background: #fff;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }
}

// 筛选标签
.filter-tags {
  margin-bottom: 30rpx;

  .tags-scroll {
    white-space: nowrap;
  }

  .tag-list {
    display: inline-flex;
    gap: 16rpx;
  }

  .filter-tag {
    display: inline-flex;
    align-items: center;
    gap: 12rpx;
    background: #e3f2fd;
    color: #1976d2;
    padding: 12rpx 20rpx;
    border-radius: 24rpx;
    font-size: 24rpx;
  }
}

// 区域样式
.section {
  margin-bottom: 40rpx;

  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    // margin-bottom: 30rpx;
    background-color: #ffffff;

    .section-title {
      display: flex;
      align-items: center;
      gap: 12rpx;

      text {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .sort-btn {
      display: flex;
      align-items: center;
      gap: 8rpx;
      padding: 12rpx 20rpx;
      background: #f8f9fa;
      border-radius: 20rpx;
      font-size: 26rpx;
      color: #666;
    }
  }
}

// 推荐展馆
.recommend-scroll {
  white-space: nowrap;
}

.recommend-list {
  display: inline-flex;
  gap: 20rpx;
}

.recommend-item {
  width: 240rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

  .recommend-image {
    width: 100%;
    height: 160rpx;
  }

  .recommend-info {
    padding: 20rpx;

    .recommend-name {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 8rpx;
    }

    .recommend-location {
      display: block;
      font-size: 24rpx;
      color: #999;
      margin-bottom: 12rpx;
    }

    .recommend-tags {
      display: flex;
      gap: 8rpx;

      .tag {
        padding: 4rpx 12rpx;
        background: #f0f0f0;
        border-radius: 12rpx;
        font-size: 20rpx;
        color: #666;
      }
    }
  }
}

// 展馆列表
.exhibition-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.exhibition-item {
  background: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  display: flex;
  align-items: flex-start;
  gap: 20rpx;

  .exhibition-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 12rpx;
    flex-shrink: 0;
  }

  .exhibition-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 200rpx;

    .exhibition-header {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      margin-bottom: 12rpx;

      .exhibition-name {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        flex: 1;
        margin-right: 16rpx;
        line-height: 1.3;
      }

      .exhibition-rating {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 4rpx;
        flex-shrink: 0;

        .rating-text {
          font-size: 24rpx;
          color: #ff6b35;
          font-weight: 500;
        }
      }
    }

    .exhibition-location {
      display: flex;
      align-items: center;
      gap: 6rpx;
      margin-bottom: 12rpx;
      font-size: 24rpx;
      color: #666;
    }

    .exhibition-details {
      display: flex;
      gap: 20rpx;
      margin-bottom: 12rpx;

      .detail-item {
        font-size: 22rpx;
        color: #999;
      }
    }

    .exhibition-tags {
      display: flex;
      gap: 8rpx;
      margin-bottom: auto;
      flex-wrap: wrap;

      .tag {
        padding: 4rpx 12rpx;
        background: #f8f9fa;
        border-radius: 12rpx;
        font-size: 20rpx;
        color: #666;
      }
    }

    .exhibition-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: auto;

      .price-info {
        display: flex;
        align-items: baseline;
        gap: 4rpx;

        .price {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff6b35;
        }

        .price-unit {
          font-size: 22rpx;
          color: #999;
        }
      }

      .exhibition-status {
        padding: 6rpx 16rpx;
        border-radius: 16rpx;
        font-size: 22rpx;

        &.available {
          background: #e8f5e8;
          color: #4caf50;
        }

        &.unavailable {
          background: #ffeaea;
          color: #f44336;
        }
      }
    }
  }
}

// 模态框样式
.search-modal {
  padding: 30rpx;
}

.filter-modal {
  padding: 40rpx 30rpx;

  .filter-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 40rpx;

    .filter-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .filter-reset {
      font-size: 28rpx;
      color: #1976d2;
    }
  }

  .filter-section {
    margin-bottom: 40rpx;

    .filter-label {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 20rpx;
    }

    .filter-options {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;

      .filter-option {
        padding: 12rpx 24rpx;
        background: #f8f9fa;
        border-radius: 24rpx;
        font-size: 26rpx;
        color: #666;

        &.active {
          background: #e3f2fd;
          color: #1976d2;
        }
      }
    }
  }

  .filter-actions {
    padding-top: 30rpx;
    border-top: 1rpx solid #f0f0f0;
  }
}
</style>